<template>
	<view class="custom_form">
		<view class="custom_form_body">
			<view class="custom_form_body_item">
				<text><text>*</text>昵称</text>
				<u-input placeholder="请输入昵称" inputAlign="right" v-model="fromValue.realname" border="none"
					:clearable="true" type="nickname" placeholderClass="placeholderClass"></u-input>
			</view>
			<button class="custom_form_body_item" open-type="chooseAvatar" @chooseavatar="handleUplad">
				<text><text>*</text>头像</text>
				<view class="custom_form_body_item_right">
					<image :src="fromValue?.avatar" v-if="fromValue?.avatar"></image>
					<!-- <image src="http://qianxueapplet.suoeryun.com/avatar.png" v-else></image> -->
					<text v-else class="placeholder">请选择头像</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</button>
			<view class="custom_form_body_item" @click="handleSex()">
				<text><text>*</text>性别</text>
				<view class="custom_form_body_item_right">
					<text v-if="fromValue?.sex">{{sexText}}</text>
					<text v-else class="placeholder">请选择</text>
					<u-icon name="arrow-right"></u-icon>
				</view>
			</view>
			<view class="custom_form_body_item">
				<text><text>*</text>手机号码</text>
				<u-input placeholder="请输入手机号码" inputAlign="right" v-model="fromValue.phone" border="none"
					:clearable="true" placeholderClass="placeholderClass"></u-input>
			</view>
			<view class="custom_form_body_item">
				<text>备用电话</text>
				<u-input placeholder="请输入备用电话" inputAlign="right" v-model="fromValue.alternatePhone" border="none"
					:clearable="true" placeholderClass="placeholderClass"></u-input>
			</view>
		</view>
		<view class="custom_form_btn" @click="handleSave">保存</view>
		<!--  性别选择-->
		<u-picker :show="isSexShow" :columns="columns" keyName="text" @confirm="handleSexConfirm"
			@cancel="handleSexCancel"></u-picker>
	</view>
</template>
<script lang="ts" setup>
	import { ref, onMounted, reactive, computed, toRaw, unref, getCurrentInstance } from "vue";
	import config from '@/common/config';
	import { getDictItemsByCode } from '@/config/sys.api';
	import { qxWxUserEdit } from '@/config/mine.api';
	import { onLoad } from "@dcloudio/uni-app";
	// import ObsClient from "esdk-obs-nodejs";
	// var ObsClient = require('esdk-obs-nodejs');

	// var obsClient = ObsClient({
	// 	//推荐通过环境变量获取AKSK，这里也可以使用其他外部引入方式传入，如果使用硬编码可能会存在泄露风险。
	// 	//您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
	// 	access_key_id: config.ACCESS_KEY_ID,
	// 	secret_access_key: config.SECRET_ACCESS_KEY,
	// 	server: 'https://qianxunyanxue-applet.obs.cn-north-4.myhuaweicloud.com'
	// });


	// 表单数据
	const fromValue = ref({ realname: '', avatar: '', sex: '', phone: '', alternatePhone: '' });
	const isSexShow = ref(false);
	const urlParams = ref();
	const columns = reactive([]);
	const { proxy } = getCurrentInstance();


	onMounted(async () => {
		let res = await getDictItemsByCode({ dictCode: 'sex' });
		columns.push(res);
		// 用户信息
		fromValue.value = JSON.parse(JSON.stringify(unref(proxy['vuex_user'])));
	});

	onLoad((params) => {
		console.log(params, 11);
		urlParams.value = params;
	})

	/**
	 * 性别中文显示
	 */
	const sexText = computed(() => {
		if (fromValue.value?.sex && columns?.length > 0) {
			let arrFilter = toRaw(columns)[0]?.filter(item => item?.value == fromValue.value?.sex);
			if (arrFilter?.length > 0) {
				return arrFilter[0]['text'];
			}
			return '';
		}
		return '';
	})

	/**
	 * 头像上传
	 */
	function handleUplad(e) {
		// obsClient.putObject({
		// 	Bucket: 'qianxunyanxue-applet',
		// 	Key: 'mini/1.png',
		// 	SourceFile: e?.detail?.avatarUrl
		// }, (err, result) => {
		// 	if (err) {
		// 		console.error('Error-->' + err);
		// 	} else {
		// 		console.log('Status-->' + result.CommonMsg.Status);
		// 	}
		// });
		uni.uploadFile({
			url: config.baseUrl + '/sys/common/obsUpload', //仅为示例，非真实的接口地址
			filePath: e?.detail?.avatarUrl,
			name: 'file',
			header: {
				'X-Access-Token': unref(proxy['vuex_token'])
			},
			success: (uploadFileRes) => {
				fromValue.value.avatar = JSON.parse(uploadFileRes.data)?.message;
				console.log(JSON.parse(uploadFileRes.data), 'uploadFile');
			},
			fail() {
				uni.showToast({
					icon: 'none',
					title: '接口异常！'
				})
			}
		});
	}

	/**
	 * 性别选择
	 */
	function handleSex() {
		isSexShow.value = true;
	}

	/**
	 * 性别选择器 确认
	 */
	function handleSexConfirm(arr) {
		console.log(arr.value[0].value, 'arr');
		if (arr?.value?.length > 0) {
			fromValue.value.sex = arr.value[0].value;
		}
		isSexShow.value = false;
	}

	/**
	 * 性别选择器 取消
	 */
	function handleSexCancel() {
		isSexShow.value = false;
	}

	/**
	 * 保存
	 */
	async function handleSave() {
		const params = unref(fromValue);
		console.log(params, 'params');
		if (params?.realname === '' || !params?.realname) {
			return uni.showToast({
				icon: 'none',
				title: '请输入昵称！'
			})
		}
		if (params?.avatar === '' || !params?.avatar) {
			return uni.showToast({
				icon: 'none',
				title: '请上传头像！'
			})
		}
		if (params?.sex === '' || !params?.sex) {
			return uni.showToast({
				icon: 'none',
				title: '请选择性别！'
			})
		}
		if (params?.phone === '' || !params?.phone) {
			return uni.showToast({
				icon: 'none',
				title: '请输入手机号码！'
			})
		}
		if (!uni.$u.test.mobile(params?.phone)) {
			return uni.showToast({
				icon: 'none',
				title: '请输入正确格式手机号码！'
			})
		}
		if (params?.alternatePhone && !uni.$u.test.mobile(params?.phone)) {
			return uni.showToast({
				icon: 'none',
				title: '请输入正确格式备用电话！'
			})
		}
		await qxWxUserEdit(params);
		// 缓存信息
		uni.$u.vuex('vuex_user', params);
		uni.showToast({
			icon: 'none',
			title: '保存成功'
		})
		// 登录过来跳转至首页
		if (unref(urlParams)?.type === 'login') {
			uni.$u.route({
				type: 'switchTab',
				url: 'pages/index/index'
			})
		} else {
			uni.$u.route({
				type: 'back',
			})
		}
	}
</script>

<style lang="scss" scoped>
</style>